package com.xuerhua.yxt.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import com.xuerhua.yxt.common.enums.ExcelTemplate;

public class JxlsExcelView extends AbstractView {
	
	private static final String CONTENT_TYPE = "application/vnd.ms-excel";

    private String templatePath;
    private String exportFileName;
    
    public JxlsExcelView(ExcelTemplate template) {
    	this.templatePath = template.getUrl();
        if (exportFileName != null) {
            try {
                exportFileName = URLEncoder.encode(template.getName(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        this.exportFileName = template.getName();
        setContentType(CONTENT_TYPE);
    }

    /**
     * @param templatePath   模版相对于当前classpath路径
     * @param exportFileName 导出文件名
     */
    public JxlsExcelView(String templatePath, String exportFileName) {
        this.templatePath = templatePath;
        if (exportFileName != null) {
            try {
                exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        this.exportFileName = exportFileName;
        setContentType(CONTENT_TYPE);
    }
    
    public JxlsExcelView() {}

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model,HttpServletRequest request,HttpServletResponse response) throws Exception {
    	
        response.setContentType(getContentType());
        response.setHeader("content-disposition",
                "attachment;filename=" + URLEncoder.encode(exportFileName, "UTF-8"));
        ServletOutputStream os = response.getOutputStream();
        File file = new File(request.getSession().getServletContext().getRealPath(templatePath));
        FileInputStream fis = null; 
        try { 
                fis = new FileInputStream(file); 
        } catch (FileNotFoundException e) { 
                e.printStackTrace(); 
        } 
        ExcelUtils.export(fis, model, os);
        os.flush();
        os.close();
    }

	public String getTemplatePath() {
		return templatePath;
	}

	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}

	public String getExportFileName() {
		return exportFileName;
	}

	public void setExportFileName(String exportFileName) {
		this.exportFileName = exportFileName;
	}
   
}
